package idv.arthur.work;



import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.tmatesoft.svn.core.ISVNDirEntryHandler;
import org.tmatesoft.svn.core.SVNCancelException;
import org.tmatesoft.svn.core.SVNDepth;
import org.tmatesoft.svn.core.SVNDirEntry;
import org.tmatesoft.svn.core.SVNException;
import org.tmatesoft.svn.core.SVNNodeKind;
import org.tmatesoft.svn.core.SVNURL;
import org.tmatesoft.svn.core.internal.wc.DefaultSVNOptions;
import org.tmatesoft.svn.core.wc.ISVNEventHandler;
import org.tmatesoft.svn.core.wc.SVNClientManager;
import org.tmatesoft.svn.core.wc.SVNEvent;
import org.tmatesoft.svn.core.wc.SVNEventAction;
import org.tmatesoft.svn.core.wc.SVNLogClient;
import org.tmatesoft.svn.core.wc.SVNRevision;
import org.tmatesoft.svn.core.wc.SVNUpdateClient;

import com.google.gson.Gson;

/**
 * Servlet implementation class DelMRitem
 */ 
public class QuerySVN extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private SVNClientManager manager;  
    private SVNURL repositoryBaseUrl; 
    static ArrayList<DirStruc> dirStrucs = new ArrayList<DirStruc>(); 
       
    public QuerySVN() {
        super();
        DefaultSVNOptions options = new DefaultSVNOptions();  
         manager = SVNClientManager.newInstance(options,  "Arthur","abcd1234"); //如果需要用戶名密碼  
        try {  
            repositoryBaseUrl = SVNURL.parseURIEncoded("http://10.144.136.56/svntest/arthur"); // 傳入svn地址  
        } catch (SVNException e) {  
            e.printStackTrace();  
        }  
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	doPost(request,response);
    }

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		request.setCharacterEncoding("UTF-8");
		
       try {
		test();
	} catch (SVNException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
		
		response.setContentType("application/json");
		response.setCharacterEncoding("UTF-8");
		response.getWriter().write(new Gson().toJson(dirStrucs));	
	}
	private class DirEntryHandler implements ISVNDirEntryHandler {  
        public void handleDirEntry(SVNDirEntry dirEntry) throws SVNException {
        	String parentDir = "沒算出來...";
        	String path = dirEntry.getRelativePath();
        	/*if ( dirEntry.getKind() == SVNNodeKind .DIR ) {		//是目錄
        		if (!path.equalsIgnoreCase("")) {
        			if (!path.contains("/")) {
        				parentDir = "root";
        			} else {
        				parentDir = path.substring(0, path.lastIndexOf(dirEntry.getName())-1);
        			}	
                	DirStruc ds = new DirStruc();
            		ds.setDir(true);
            		ds.setHome(parentDir);
            		ds.setId(path);
            		dirStrucs.add(ds);
            	}
        		
        	} else*/ if ( dirEntry.getKind() == SVNNodeKind.FILE ) {	
        		if (!path.contains("/")) {
    				parentDir = "root";
    			} else {
    				parentDir = path.substring(0, path.lastIndexOf(dirEntry.getName())-1);
    			}	
        		DirStruc ds = new DirStruc();
        		ds.setDir(false);
        		ds.setHome(parentDir);
        		//ds.setId(dirEntry.getName());
        		ds.setId(dirEntry.getName().replaceAll("\\.","__"));
        		ds.setVer(dirEntry.getRevision());
        		dirStrucs.add(ds);
        	} /*else {
        		System.out.println("有問題"+dirEntry.getKind());
        	}
        	*/
        	 
            //System.out.println(dirEntry.getRelativePath() + "/" + dirEntry.getName()+"====>一定現在DirEntryHandler裡的Revision是："+  dirEntry.getRevision());
        }  
    }
	
	 private void test() throws SVNException {  
	        SVNLogClient logClient = manager.getLogClient();  
	  
	        // svn list  
	        DirEntryHandler handler = new DirEntryHandler(); // 在svn
	        
	        // co時對每個文件目錄的處理，實現ISVNDirEntryHandler接口  
	        logClient.doList(repositoryBaseUrl, SVNRevision.HEAD, SVNRevision.HEAD,false, true, handler); // 列出當前svn地址的目錄，對每個文件進行處理  
	        // svn co  
	        UpdateEventHandler svnEventHandler = new UpdateEventHandler(); // svn  co時對每個文件的處理  
	        SVNUpdateClient client = manager.getUpdateClient();  
	        client.setIgnoreExternals(true);  
	        client.setEventHandler(svnEventHandler);  
	        File to = new File("D:\\temp"); // co出來的文件存放目錄  
	        client.doCheckout(repositoryBaseUrl, to, SVNRevision.HEAD, SVNRevision.HEAD, SVNDepth.INFINITY, false);  
	        // svn update  
	        client.setIgnoreExternals(true);  
	        client.setEventHandler(svnEventHandler);   
	        client.doUpdate(to, SVNRevision.HEAD, SVNDepth.INFINITY,true, false);  
	  
	    }
	 
	 private class UpdateEventHandler implements ISVNEventHandler {  
		  
		    public void handleEvent(SVNEvent event, double progress) {  
		        SVNEventAction action = event.getAction();  
		        SVNNodeKind nodeKind = event.getNodeKind();  
		
		        if (SVNNodeKind.DIR.equals(nodeKind)) {  
		            // folder  
		                System.out.println(event.getFile().getName()+"====>現的Revision是："+  event.getRevision());  
		        } else {  
		            // treat as file for all other type
		        	
		            if (action == SVNEventAction.UPDATE_DELETE) {  
		                try {
		                    System.out.println(event.getFile().getName() + "\t" + FileUtils.readFileToString(event.getFile())+"====>現的Revision是："+  event.getRevision());  
		                    
		                } catch (IOException e) {  
		  
		                }  
		            } else if (action == SVNEventAction.UPDATE_ADD || action == SVNEventAction.UPDATE_UPDATE) {  
		                try {  
		                    System.out.println(event.getFile().getName() + "\t" + FileUtils.readFileToString(event.getFile())+"====>現的Revision是："+  event.getRevision());  
		                    
		                } catch (IOException e) {  
		  
		                }  
		            }  
		        }  
		    }  
		  
		    public void checkCancelled() throws SVNCancelException {  
		    }  
		  
		}
	 class DirStruc {
			boolean isDir;
			long ver;
			String id;
			String home;
			public boolean isDir() {
				return isDir;
			}
			public void setDir(boolean isDir) {
				this.isDir = isDir;
			}
			public long getVer() {
				return ver;
			}
			public void setVer(long ver) {
				this.ver = ver;
			}
			public String getId() {
				return id;
			}
			public void setId(String id) {
				this.id = id;
			}
			public String getHome() {
				return home;
			}
			public void setHome(String home) {
				this.home = home;
			}
			
		}
}